<template>
  <view class="important-devices">
    <!-- 重点电器监测 -->
    <view class="monitoring-section">
      <view class="section-title">
        <text class="title-text">重点电器监测</text>
      </view>

      <!-- 筛选器 -->
      <view class="area-filter-income">
        <areaFilterVue
          ref="areaFilterRef"
          :filterConfig="filterConfig"
          :areaData="areaStore.areaData"
          @filterChange="handleFilterChange"
        ></areaFilterVue>
      </view>

      <!-- 数据表格 -->
      <view class="table-container">
        <view class="table-header">
          <view class="header-cell area-cell">
            <image
              class="power-icon"
              src="/static/img/components/power-icon.png"
              mode="widthFix"
            ></image>
          </view>
          <view class="header-cell">监控设备</view>
          <view class="header-cell">电器</view>
          <view class="header-cell">所属</view>
          <view class="header-cell">数据</view>
        </view>

        <!-- 使用 swiper 组件 -->
        <tn-swiper
          v-model="currentTableIndex"
          :data="allTableData"
          :indicator="false"
          :autoplay="false"
          :loop="false"
          :height="swiperHeight + 'rpx'"
          @change="onSwiperChange"
        >
          <template #default="{ data: table, index }">
            <scroll-view class="table-body" scroll-y>
              <view
                class="table-row"
                v-for="(item, idx) in table.data"
                :key="idx"
              >
                <view class="header-cell area-cell">
                  <view class="area-info">
                    <text class="area-name">{{ item.area }}</text>
                  </view>
                </view>
                <view class="row-cell">{{ item.device }}</view>
                <view class="row-cell">{{ item.appliance }}</view>
                <view class="row-cell">{{ item.company }}</view>
                <view class="row-cell">
                  <text
                    class="analyze-link"
                    @click="
                      mygo('/pages/consolePages/on-off', { Id: item.device })
                    "
                    >分析</text
                  >
                </view>
              </view>
            </scroll-view>
          </template>
        </tn-swiper>

        <image
          class="table-bottom"
          src="/static/img/components/table-bottom.png"
          mode="widthFix"
        ></image>
      </view>
    </view>

    <!-- 重点电器分布图 -->
    <view class="section-title-chart">
      <text class="chart-title-text">重点电器分布图</text>
    </view>
    <view class="distribution-section">
      <!-- 词云图 -->
      <view class="wordcloud-container">
        <qiun-data-charts
          type="word"
          :opts="wordcloudOpts"
          :chartData="wordcloudData"
          background="rgba(255,255,255,0)"
        />
      </view>

      <!-- 说明文字 -->
      <view class="wordcloud-desc">
        <text class="desc-text"
          >词云展示数据为页面上方重点电器监测表格筛选所得</text
        >
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch, computed } from 'vue';
import { createRequest } from '@/utils/request';
import areaFilterVue from '@/components/areaFilter.vue';
import { mygo } from '@/utils/useNavigator';
import { useAreaStore } from '@/store/area';

// 区域数据管理
const areaStore = useAreaStore();

// 所有区域的mock表格数据，结构参考homeView
// 保留这一段
const allTableData = ref([]);

// 区域筛选器配置
const filterConfig = ref({
  labels: ['校区', '区域', '建筑'],
});

// 移除旧的筛选数据变量，因为新的筛选组件会从areaData自动构建
// const filter1List = computed(() => areaStore.getFilter1List)
// const filter2List = ref([])

// 当前选中二级区域索引
const currentTableIndex = ref(0);

// 区域筛选器引用
const areaFilterRef = ref(null);

// 处理筛选器变化
const handleFilterChange = async filterData => {
  console.log('筛选变化:', filterData);
  
  // 获取当前筛选层级数据
  const currentLevels = areaFilterRef.value?.filterLevels || [];
  
  // 检查是否有有效的筛选数据
  if (currentLevels.length === 0) {
    console.log('没有筛选层级数据');
    return;
  }
  
  // 获取最后一级筛选
  const lastLevel = currentLevels[currentLevels.length - 1];
  if (!lastLevel || lastLevel.options.length === 0) {
    console.log('最后一级筛选没有选项');
    allTableData.value = [];
    currentTableIndex.value = 0;
    updateSwiperHeight();
    return;
  }
  
  // 检查是否选择了"全部"
  const selectedOption = lastLevel.options[lastLevel.selectedIndex];
  if (selectedOption && selectedOption.value === 'all') {
    console.log('选择了全部，清空数据');
    allTableData.value = [];
    currentTableIndex.value = 0;
    updateSwiperHeight();
    return;
  }
  
  // 动态判断筛选类型和层级
  const currentLevelIndex = parseInt(filterData.type.replace('filter', '')) - 1;
  const isLastLevel = currentLevelIndex === currentLevels.length - 1;
  
  console.log(`当前筛选层级: ${currentLevelIndex + 1}, 总层级数: ${currentLevels.length}, 是否最后一级: ${isLastLevel}`);
  
  if (isLastLevel) {
    // 最后一级筛选变化：同步swiper索引
    const targetIndex = filterData.targetIndex;
    if (targetIndex !== undefined && targetIndex >= 0 && targetIndex < allTableData.value.length) {
      console.log('同步swiper索引到:', targetIndex);
      currentTableIndex.value = targetIndex;
      updateSwiperHeight();
    }
  } else {
    // 非最后一级筛选变化：重新获取数据
    console.log('重新获取数据');
    await fetchTableData(filterData);
    currentTableIndex.value = 0;
    updateSwiperHeight();
  }
};

// 获取表格数据
const fetchTableData = async filterData => {
  try {
    let mockData = [];

    // 获取当前筛选层级数据
    const currentLevels = areaFilterRef.value?.filterLevels || [];

    // 根据筛选级别获取数据
    if (currentLevels.length > 0) {
      // 找到最后一级筛选（最深层级）
      const lastLevel = currentLevels[currentLevels.length - 1];

      if (lastLevel && lastLevel.options.length > 0) {
        // 每个最后一级筛选的选项对应一个swiper item
        mockData = generateTableDataFromLastLevelOptions(
          lastLevel.options,
          filterData
        );
      }
    }

    allTableData.value = mockData;
  } catch (error) {
    console.error('获取表格数据失败:', error);
    allTableData.value = [];
  }
};

// 根据最后一级区域的所有选项生成表格数据
const generateTableDataFromLastLevelOptions = (
  lastLevelOptions,
  filterData
) => {
  // 每个最后一级区域选项对应一个swiper item
  return lastLevelOptions.map(option => ({
    title: option.label,
    data: [
      {
        area: option.label,
        device: `${option.value}01`,
        appliance: '电器A',
        company: '公司A',
      },
      {
        area: option.label,
        device: `${option.value}02`,
        appliance: '电器B',
        company: '公司B',
      },
      {
        area: option.label,
        device: `${option.value}03`,
        appliance: '电器C',
        company: '公司C',
      },
      {
        area: option.label,
        device: `${option.value}04`,
        appliance: '电器D',
        company: '公司D',
      },
      {
        area: option.label,
        device: `${option.value}05`,
        appliance: '电器E',
        company: '公司E',
      },
    ],
  }));
};

// 词云配置
const wordcloudOpts = reactive({
  color: ['#1890FF', '#1ec8e1', '#04FBF8', '#096BDA'],
  enableScroll: false,
  extra: {
    word: {
      type: 'normal',
      autoColors: true,
    },
  },
});

// 词云数据
const wordcloudData = ref({
  series: [
    {
      name: '电器-3',
      textSize: 25,
      data: undefined,
    },
    {
      name: '电器-2',
      textSize: 20,
      data: undefined,
    },
    {
      name: '电器-1',
      textSize: 20,
      data: undefined,
    },
    {
      name: '电器0',
      textSize: 20,
      data: undefined,
    },
    {
      name: '电器1',
      textSize: 20,
      data: undefined,
    },
    {
      name: '电器2',
      textSize: 20,
      data: undefined,
    },
    {
      name: '电器3',
      textSize: 20,
      data: undefined,
    },
    {
      name: '电器4',
      textSize: 20,
      data: undefined,
    },
    {
      name: '电器5',
      textSize: 10,
      data: undefined,
    },
    {
      name: '电器6',
      textSize: 12,
      data: undefined,
    },
    {
      name: '电器7',
      textSize: 10,
      data: undefined,
    },
    {
      name: '电器8',
      textSize: 12,
      data: undefined,
    },
    {
      name: '电器9',
      textSize: 10,
      data: undefined,
    },
    {
      name: '电器10',
      textSize: 12,
      data: undefined,
    },
    {
      name: '电器11',
      textSize: 10,
      data: undefined,
    },
    {
      name: '电器12',
      textSize: 12,
      data: undefined,
    },
  ],
});

// 获取词云数据
const fetchData = async () => {
  try {
    // 这里可以根据实际需求获取词云数据
    // const response = await createRequest('/api/wordcloud', {
    //   method: 'GET',
    //   showLoading: false
    // })
    // wordcloudData.value = response.data
  } catch (error) {
    console.error('获取词云数据失败:', error);
  }
};

// 初始化时自动选中第一个一级和二级区域，并获取词云数据
onMounted(async () => {
  // 区域数据已在登录时获取，无需重复获取
  if (!areaStore.areaDataLoaded) {
    console.warn('区域数据未加载，可能登录时获取失败');
  }

  // 等待筛选组件初始化完成后，触发初始数据加载
  await nextTick();

  // 等待筛选组件完全初始化
  await new Promise(resolve => setTimeout(resolve, 100));

  // 新的筛选组件会自动选择第一个选项，我们只需要触发一次数据加载
  if (areaStore.areaData.length > 0) {
    // 模拟一级筛选变化，触发数据加载
    await handleFilterChange({
      type: 'filter1',
      filter1: areaStore.areaData[0],
    });
  }

  // 获取词云数据
  await fetchData();
});

// swiper 变化事件处理
const onSwiperChange = idx => {
  // 获取当前筛选层级数据
  const currentLevels = areaFilterRef.value?.filterLevels || [];

  // 如果有筛选层级，同步更新最后一级筛选组件
  if (currentLevels.length > 0) {
    const lastLevelIndex = currentLevels.length - 1;
    const lastLevel = currentLevels[lastLevelIndex];
    if (lastLevel && idx < lastLevel.options.length) {
      // 使用新的筛选组件API更新最后一级索引
      areaFilterRef.value?.updateLevelIndex(lastLevelIndex, idx);
    }
  }
  updateSwiperHeight();
};

const swiperHeight = ref(0);

const updateSwiperHeight = () => {
  nextTick(() => {
    if (allTableData.value.length === 0) {
      swiperHeight.value = 0;
      return;
    }
    const currentTableData = allTableData.value[currentTableIndex.value];
    if (currentTableData) {
      const itemCount = currentTableData.data?.length || 0;
      const maxVisibleRows = 5; // 可根据实际需求调整
      const visibleRows = Math.min(itemCount, maxVisibleRows);
      const rowHeight = 80; // 你的 .table-row 的高度
      const borderPerRow = 1; // border-bottom: 1rpx
      const estimatedHeight =
        visibleRows > 0
          ? visibleRows * rowHeight + (visibleRows - 1) * borderPerRow
          : 0;
      swiperHeight.value = estimatedHeight;
    }
  });
};

watch([allTableData, currentTableIndex], updateSwiperHeight, {
  immediate: true,
});
</script>

<style scoped lang="scss">
.important-devices {
  padding: 20rpx;
  box-sizing: border-box;
}

.monitoring-section {
  margin-bottom: 40rpx;
}

.distribution-section {
  width: 686rpx;
  height: 554rpx;
  background-image: url('/static/img/components/chart-section.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  overflow: hidden;
  position: relative;
}

.section-title-chart {
  width: 100%;
  height: 68rpx;
  background-image: url('/static/img/homePages/chart-title.png');
  background-size: 100% 100%;
}

.chart-title-text {
  font-size: 36rpx;
  color: #fff;
  letter-spacing: 3rpx;
  font-family: 'YouSheBiaoTiHei';
  line-height: 68rpx;
  margin-left: 60rpx;
}

.section-title {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 694rpx;
  height: 88rpx;
  background-image: url('/static/img/components/section-title.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
}

.title-text {
  font-size: 36rpx;
  font-weight: bold;
  color: #fff;
  letter-spacing: 3rpx;
  margin-bottom: 8rpx;
}

.area-filter-income {
  width: 100%;
  height: 120rpx;
  border-left: 1rpx solid #1ec8e1;
  border-right: 1rpx solid #1ec8e1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(to bottom, #0b317f 0%, #092367 100%);
}

// 表格样式
.table-container {
  width: 100%;
  border-left: 1rpx solid #1ec8e1;
  border-right: 1rpx solid #1ec8e1;
  background: linear-gradient(to bottom, #092367 0%, #061845 100%);
  position: relative;
}

.table-bottom {
  position: absolute;
  bottom: -12rpx;
  left: -6rpx;
  width: 703rpx;
}

.table-header {
  display: flex;
  border-bottom: 1rpx solid #2a4a7a;
}

.header-cell {
  flex: 1;
  padding: 20rpx 16rpx;
  text-align: center;
  font-size: 24rpx;
  font-weight: bold;
  color: #fff;
  min-width: 120rpx;
  box-sizing: border-box;
}

.area-cell {
  flex: 1.5;
  min-width: 130rpx;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  display: flex;
  align-items: center;
  justify-content: center;
}

.power-icon {
  width: 48rpx;
  height: 48rpx;
}

.table-body {
  max-height: 400rpx;

  /* 隐藏滚动条 */
  &::-webkit-scrollbar {
    display: none;
  }

  /* 兼容其他浏览器 */
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.table-row {
  display: flex;
  border-bottom: 1rpx solid #2a4a7a;
  height: 80rpx;
  box-sizing: border-box;

  &:last-child {
    border-bottom: none;
  }
}

.row-cell {
  flex: 1;
  padding: 20rpx 16rpx;
  text-align: center;
  font-size: 24rpx;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 120rpx;
  box-sizing: border-box;
}

.area-info {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  width: 100%;
}

.area-name {
  font-size: 24rpx;
  color: #fff;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

.analyze-link {
  color: #04fbf8;
  font-size: 24rpx;
  transition: all 0.3s ease;
}

.analyze-link:active {
  color: #1a8f3d;
  transform: scale(0.95);
}

// 词云容器
.wordcloud-container {
  height: 380rpx;
  width: 580rpx;
  position: absolute;
  top: 70rpx;
  left: 50%;
  transform: translateX(-50%);
  background-image: url('/static/img/components/word-stream.png');
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}

// 说明文字样式
.wordcloud-desc {
  width: 100%;
  text-align: center;
  position: absolute;
  bottom: 40rpx;
  left: 50%;
  transform: translateX(-50%);
}

.desc-text {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.6);
  line-height: 1.5;
}
</style>
